package com.wei.web.middleware.httpfilter.registrar.filter;

import com.alibaba.fastjson.JSONObject;
import com.wei.web.middleware.httpfilter.registrar.filter.factory.CorsFilterRegistrarFactoryBean;
import com.wei.web.middleware.httpfilter.registrar.filter.factory.FactoryFilterRegistrarFactoryBean;
import com.wei.web.middleware.httpfilter.registrar.model.CorsConfigDTO;
import com.wei.web.middleware.httpfilter.registrar.model.FilterConfigDTO;
import com.wei.web.middleware.httpfilter.registrar.model.RegisterContext;
import com.wei.web.middleware.httpfilter.utils.ZvaCorsRegistry;
import lombok.Data;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistration;

import java.util.List;

public class CorsFilterRegistrar extends AbstractFilterRegistrar {
    public static final String TYPE = "cors";

    @Override
    public String getType() {
        return TYPE;
    }

    @Override
    public void registrar(FilterConfigDTO filterConfigDTO, BeanDefinitionRegistry registry, RegisterContext registerContext) {
        String filterName = getFilterNameWithDefault(filterConfigDTO, registerContext);
        doRegisterCorsFilter(filterConfigDTO, filterName, registerContext.getFilterOrder(),
                filterConfigDTO.getUrlPatterns(),
                registry);
    }

    protected void doRegisterCorsFilter(FilterConfigDTO filterConfig,
                                                 String filterName,
                                                 Integer order,
                                                 List<String> urlPatterns,
                                                 BeanDefinitionRegistry registry
    ) {

        BeanDefinitionBuilder builder1 = BeanDefinitionBuilder.genericBeanDefinition(CorsFilterRegistrarFactoryBean.class);
        builder1.addPropertyValue("filterConfig", filterConfig);
        builder1.addPropertyValue("filterName", filterName);
        builder1.addPropertyValue("filterOrder", order);
        builder1.addPropertyValue("urlPatterns", urlPatterns);
        String beanName = filterName + FactoryFilterRegistrarFactoryBean.class.getSimpleName();
        registry.registerBeanDefinition(beanName, builder1.getBeanDefinition());
    }

}
